import { Component, Host, ViewChild } from "@angular/core";
import { AppComponent } from "../../../app.component";
import { ToolsService } from "../tools.service";
import { ToasterService } from "angular2-toaster";
import { FileUploader } from "ng2-file-upload";
import { StorageService } from "../../../shared/services/storage.service";

@Component({
    templateUrl: './percentile.component.html',
    providers: [ToolsService]
})
export class PercentileComponent {
    public fileUploader: FileUploader;
    public canUpload: boolean = false;

    @ViewChild('selectedFile') selectedFile: any;

    constructor(@Host() private rootComponent: AppComponent,
        private toolsService: ToolsService,
        private toasterService: ToasterService) { }

    ngOnInit() {        
        this.rootComponent.finishLoading();
        this.fileUploader = new FileUploader({});
        this.fileUploader.onAfterAddingFile = (data: any) => {
            let auth = StorageService.get().authData;
            data.withCredentials = false;
            this.fileUploader.setOptions(
                {
                    authToken: `Bearer ${auth.access_token}`,
                    url: this.toolsService.getServerUrl() + 'esgratingserv/api/v1/esgfocusthreshold',
                    method: 'POST',
                    headers: [
                        { name: 'Content-Disposition', value: 'form-data; filename="' + data.file.name + '"' }
                    ]
                }
            );
            //show upload button
            this.canUpload = true;
        }      

        this.fileUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.toasterService.pop('success', 'Success', 'File uploaded successfully');            
            this.clearSelectedFile();
        };

        this.fileUploader.onErrorItem = _ => {
            this.toasterService.pop('warning', 'Warning', 'There was an error encountered while trying to upload the file selected');
            this.clearSelectedFile();
        }
    }

    public upload() {
        this.fileUploader.uploadAll();
    }

    private clearSelectedFile() {
        this.selectedFile.nativeElement.value = '';
    }
}